package com.attendance.www.hr.controller;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;





import com.attendance.www.hr.beans.AttachmentBean;
import com.attendance.www.hr.constant.AppConstant;
import com.attendance.www.hr.service.IAttachmentService;
import com.zhangkongli.frame.upload.HTTPUploader;

@Controller
@RequestMapping(value="/upload")
public class UploadController {
	
	@Resource
	private IAttachmentService AttachmentService;
	
	
	@ResponseBody
	@RequestMapping(value="/uploadToken.do")
	public Object getUploadToken(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		return HTTPUploader.getUploadToken(req, resp,"hash_fileSize_lll");
	}
	
	@ResponseBody
	@RequestMapping(value="/upload.do")
	public Object uploadTest(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Map<String,Object> result = HTTPUploader.upload(req, resp);
		if(result.size()==3){
			Object file = result.get("name");
			String path = AppConstant.STREAM_FILE_REPOSITORY +"/"+ file.toString();
			UUID uuid = UUID.randomUUID();
			String newPath = AppConstant.SAVE_FILE_REPOSITORY +"/"+uuid.toString();
			File dir = new File(newPath);
			if(!dir.exists()){
				dir.mkdirs();
			}
			File oldFile = new File(path);
			String fileName = req.getParameter("name");
			oldFile.renameTo(new File(newPath+"/"+fileName));
			String relativeUri = AppConstant.UPLOAD_RESOURCE +"/"+uuid.toString()+"/"+ fileName;
			AttachmentBean bean = AttachmentService.addAttachment(relativeUri, fileName);
			result.put("newName", relativeUri);
			result.put("attachment", bean);
		}
		return result;
	}
}
